
'use strict';
define(['app', 'utils/route-config'], function (app, routeConfig) {
	
    /**
	* Accounting services
	*/
	app.factory("accountServices", function($http) {
		var accounts = [];
		return {
			initialize: function(callback) {
				console.log('initialize accountServices');
				$http.post(app.serviceBase, { "service" : "getAccounts"}).
				success(function(data, status) 
				{
					console.info("accountServices.getAccounts - call success"); 
					accounts = data.response;
					callback(accounts);
				})
				.
				error(function(data, status) 
				{
					console.info("accountServices.getAccounts - call failed"); 
					throw status + ' : ' + data;
				});
			},
			all: function(callback) {
				callback(accounts);
			},
			add: function(callback, state, name) {
				console.log('accountServices.addAccount called');
				$http.post(app.serviceBase, { "service" : "addAccount", "state": state, "name": name }).
				success(function(data, status) 
				{	
					console.info("accountServices.addAccount - call success"); 
					accounts.push(data.response);
					callback(data);
				})
				.
				error(function(data, status) 
				{
					console.info("accountServices.addAccount - call failed"); 
					throw status + ' : ' + data;
				});
			},
			deleteAccount: function(callback, account) {
				console.log('accountServices.deleteAccount called');
				$http.post(app.serviceBase, { "service" : "deleteAccount", "id": account.Id }).
				success(function(data, status) 
				{	
					console.info("accountServices.deleteAccount - call success"); 
					
					var index = -1;
					for(var i = 0; i < accounts.length; i++)
					{
						var localAccount = accounts[i];
						if(localAccount.Id == account.Id)
						{
							index = i;
							break;
						}
					}
					if (index > -1) {
						accounts.splice(index, 1);
					}
					callback(accounts);
				})
				.
				error(function(data, status) 
				{
					console.info("accountServices.deleteAccount - call failed"); 
					throw status + ' : ' + data;
				});
			}
		};
	});

    return app;
});